package com.way.demo.filter;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletRequest;
import java.io.IOException;
import java.io.Reader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lipingwei
 * @create 2021-01-28 15:38
 */
public class HttpRequestUtil {

    public static Map<String,Object> getRequestParamMap(ServletRequest requestWrapper) throws IOException {
        Map<String, Object> paramMap = new HashMap<>();
        String contentType = requestWrapper.getContentType();
        Reader reader = requestWrapper.getReader();
        // 读取Request Payload数据
        String body = IoUtil.read(reader);
        if (contentType != null && contentType.startsWith("application/json")) {
            JSONObject jsonObject = JSON.parseObject(body);
            if (jsonObject != null) {
                for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                    paramMap.put(entry.getKey(), entry.getValue());
                }
            }
        } else if (contentType != null && contentType.startsWith("text/plain")) {
            String[] kvs = body.split("&");
            for (String kv : kvs) {
                String[] lf = kv.split("=");
                paramMap.put(lf[0], lf[1]);
            }

        }
        Enumeration en = requestWrapper.getParameterNames();
        while (en.hasMoreElements()) {
            String name = (String) en.nextElement();
            String value = requestWrapper.getParameter(name);
            paramMap.put(name, value);
        }
        return paramMap;
    }




}
